package com.cakemallproject.controller;

import com.cakemallproject.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {
    //项目源目录
    static final String srcPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\image\\";
    //项目部署目录
    static final String tarPath = System.getProperty("user.dir") + "\\target\\classes\\static\\image\\";
    static {
        File srcFile = new File(srcPath);
        if (!srcFile.isDirectory()) {
            srcFile.mkdirs();
        }
        File tarFile = new File(tarPath);
        if (!tarFile.isDirectory()) {
            tarFile.mkdirs();
        }
    }
    @PostMapping("/goods_cover")
    public Result uploadGoodsCover(MultipartFile file) {
        log.info("商品封面文件上传");
        String flag = UUID.randomUUID().toString().replaceAll("-","") + "-";
        String filePath_src = srcPath + flag + file.getOriginalFilename();
        String filePath = tarPath + flag + file.getOriginalFilename();
        try {
            BufferedInputStream bis = new BufferedInputStream(file.getInputStream());
            byte[] allBytes = bis.readAllBytes();
            //上传到源目录（开发阶段使用）
            File imageFile_src = new File(filePath_src);
            if (!imageFile_src.exists()) {
                imageFile_src.createNewFile();
            }
            BufferedOutputStream bos_src = new BufferedOutputStream(new FileOutputStream(imageFile_src));
            bos_src.write(allBytes);
            //上传到部署目录
            File imageFile = new File(filePath);
            if (!imageFile.exists()) {
                imageFile.createNewFile();
            }
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(imageFile));
            bos.write(allBytes);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("文件上传失败！！！");
        }
        log.info("商品封面文件上传成功");
        return Result.success("http://127.0.0.1:8080/image/" + flag + file.getOriginalFilename());
    }
}
